package top.healthylife.basics.utils.config.feign;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.healthylife.basics.utils.utils.SpringContextUtil;
import top.healthylife.basics.utils.utils.TenantContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * Feign增强
 *
 * @author maoxiaomeng
 */
@Slf4j
@Configuration
public class FeignInterceptorConfig {

    @Bean
    @ConditionalOnMissingBean(value = {RequestInterceptor.class})
    public RequestInterceptor feignInterceptor() {
        return requestTemplate -> {
            String applicationContextName = SpringContextUtil.getApplicationContextName();
            requestTemplate.header("_application_name_", applicationContextName);
            if (StrUtil.isBlank(TenantContextHolder.getTenantId())) {
                requestTemplate.header("tenantId", "1");
                log.trace("TTL 中的 租户ID为空，feign拦截器 >> 增强失败");
            } else {
                requestTemplate.header("tenantId", TenantContextHolder.getTenantId());
            }
            // 共享租户id
            requestTemplate.header("shareTenantIds", URLEncoder.encode(JSONUtil.toJsonStr(TenantContextHolder.getShareTenantIds())));
            // 传递用户信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(attributes)) {
                HttpServletRequest request = attributes.getRequest();
                String user = request.getHeader("user");
                if (StringUtils.isNotBlank(user) && !"undefined".equalsIgnoreCase(user)) {
                    requestTemplate.header("user", user);
                }
            }
            log.trace("发送Feign请求: {}, 传递租户：{}", requestTemplate.path(), TenantContextHolder.getTenantId());
        };
    }

}
